<template>
  <div class="app-container">
    <el-form v-show="showSearch" ref="queryForm" :model="queryParams" size="small" :inline="true" label-width="68px">
      <!-- <el-form-item label="学号" prop="stuId">
        <el-input
          v-model="queryParams.stuId"
          placeholder="请输入学号"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item> -->
      <el-form-item label="姓名" prop="stuName">
        <el-input
          v-model="queryParams.stuName"
          placeholder="请输入"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="任务" prop="period" label-width="95px">
        <el-input
          v-model="queryParams.period"
          placeholder="请输入任务"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          v-hasPermi="['system:score_info:add']"
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
        >新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          v-hasPermi="['system:score_info:edit']"
          type="success"
          plain
          icon="el-icon-edit"
          size="mini"
          :disabled="single"
          @click="handleUpdate"
        >修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          v-hasPermi="['system:score_info:remove']"
          type="danger"
          plain
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple"
          @click="handleDelete"
        >删除</el-button>
      </el-col>
      <!-- <el-col :span="1.5">
        <el-button
          v-hasPermi="['system:score_info:export']"
          type="warning"
          plain
          icon="el-icon-download"
          size="mini"
          @click="handleExport"
        >导出</el-button>
      </el-col> -->
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="el-icon-delete"
          size="mini"
          @click="handleDeleteAll"
        >删除所有数据</el-button>
      </el-col>

      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleBatchAdd"
        >批量新增</el-button>
      </el-col>
      <right-toolbar :show-search.sync="showSearch" @queryTable="getList" />
    </el-row>

    <el-table v-loading="loading" :data="score_infoList" height="600px" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="打分类型" align="center" prop="scoreType">
        <template slot-scope="scope">
          <dict-tag :options="dict.type.score_type" :value="scope.row.scoreType" />
        </template>
      </el-table-column>
      <!-- <el-table-column label="学号" align="center" prop="stuId" /> -->
      <el-table-column label="姓名" align="center" prop="stuName" />
      <el-table-column label="任务" align="center" prop="period" />
      <el-table-column label="科目名称" align="center" prop="subjectName">
        <template slot-scope="scope">
          <span
            v-for="item in scope.row.subjectName.split(',')"
            :key="item"
          >
            <dict-tag :options="getDict(scope.row.scoreType)" :value="item" />
          </span>
        </template>
      </el-table-column>
      <el-table-column label="分数" align="center" prop="score" />
      <!-- <el-table-column label="打分人id" align="center" prop="scorerId" />
      <el-table-column label="打分人" align="center" prop="scorer" /> -->
      <el-table-column label="备注" align="center" prop="remark" />
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button
            v-hasPermi="['system:score_info:edit']"
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
          >修改</el-button>
          <el-button
            v-hasPermi="['system:score_info:remove']"
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
          >删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改分数信息对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="600px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="100px">
        <el-form-item label="学号" prop="stuId">
          <el-select
            v-model="form.stuId"
            placeholder="请选择学号"
            clearable
            filterable
            value-key="stuId"
            @change="changeStu"
          >
            <el-option
              v-for="dict in infoList"
              :key="dict.stuId"
              :label="`${dict.grade}(${dict.stuName})`"
              :value="dict"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="姓名" prop="stuName">
          <el-input v-model="form.stuName" placeholder="姓名" disabled style="width: 48%;" />
        </el-form-item>
        <el-form-item label="任务名" prop="period">
          <el-select
            v-model="form.period"
            placeholder="请选择任务名"
            clearable
            filterable
            value-key="stuId"
            @change="changeTask"
          >
            <el-option
              v-for="(dict, index) in taskNameList"
              :key="index"
              :label="dict.taskName"
              :value="dict"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="打分类型" prop="scoreType">
          <el-select v-model="form.scoreType" placeholder="请选择类型" clearable @change="changeType">
            <el-option
              v-for="dict in dict.type.score_type"
              :key="dict.value"
              :label="dict.label"
              :value="dict.value"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="">
          <div>
            <div class="subject_score">
              <span class="item">科目名称</span>
              <span class="item">分数</span>
            </div>
            <div
              v-for="(dict, key) in typeList"
              :key="dict.value"
              class="subject_score"
            >
              <span>{{ dict.label }}：</span>
              <el-input-number
                v-model="scoreList[key]"
                placeholder="请输入分数"
                style="width: 50%;"
                :min="0"
                :max="100"
                :precision="0"
              />
            </div>
          </div>
        </el-form-item>
        <el-form-item label="备注" prop="remark">
          <el-input v-model="form.remark" type="textarea" placeholder="请输入内容" />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>

    <el-dialog :title="title" :visible.sync="showDialog" width="400px" append-to-body>
      <el-form ref="form" :inline="true" label-width="80px">
        <el-checkbox v-model="checkAll" :indeterminate="isIndeterminate" @change="handleCheckAllChange">全选</el-checkbox>
        <div style="margin: 15px 0;" />
        <el-checkbox-group v-model="checkTaskOptions" @change="handleCheckedCitiesChange">
          <el-checkbox v-for="(task, i) in taskOptions" :key="i" :label="task">{{ task.taskName }}</el-checkbox>
        </el-checkbox-group>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="doNext">确 定</el-button>
        <el-button @click="showDialog = false">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { listScore_info, getScore_info, delScore_info, addScore_info, updateScore_info } from '@/api/system/scoreInfo'
import { studentInfo } from '@/api/system/studentInfo'
import { taskList } from '@/api/system/taskList'

export default {
  name: 'ScoreInfo',
  dicts: ['score_type', 'peer_review', 'teacher_eval', 'expert_joint_eval', 'platform_eval', 'supervisor_eval'],
  data() {
    return {
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 分数信息表格数据
      score_infoList: [],
      // 弹出层标题
      title: '',
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        stuId: null,
        stuName: null,
        period: null,
        subjectName: null,
        score: null,
        scorerId: null,
        scorer: null,
        scoreType: null
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        scoreType: [
          { required: true, message: '打分类型不能为空', trigger: 'blur' }
        ],
        stuId: [
          { required: true, message: '学号不能为空', trigger: 'blur' }
        ],
        period: [
          { required: true, message: '年度或期次不能为空', trigger: 'blur' }
        ],
        // subjectName: [
        //   { required: true, message: "科目名称不能为空", trigger: "blur" }
        // ],
        score: [
          { required: true, message: '分数不能为空', trigger: 'blur' }
        ]
      },
      infoList: [],
      typeName: 'peer_review',
      typeList: [],
      scoreList: [],
      optType: 'add',
      scoreTypeList: [
        { key: '0', value: 'peer_review' },
        { key: '1', value: 'teacher_eval' },
        { key: '2', value: 'expert_joint_eval' },
        { key: '3', value: 'platform_eval' },
        { key: '4', value: 'supervisor_eval' }
      ],
      taskNameList: [],
      checkAll: false,
      checkTaskOptions: [],
      taskOptions: [],
      isIndeterminate: true,
      showDialog: false
    }
  },
  created() {
    this.getTaskList()
    this.getStuList()
    this.getList()
    this.changeType('0')
    this.changeType()
  },
  methods: {
    handleDeleteAll() {
      listScore_info({ pageNum: 1, pageSize: 5000 }).then((response) => {
        const ids = response.rows.map((item) => item.id)
        ids.length && this.handleDelete({ ids })
      })
    },
    handleBatchAdd() {
      this.showDialog = true
    },
    handleCheckAllChange(val) {
      this.checkTaskOptions = val ? this.taskOptions : []
      this.isIndeterminate = false
    },
    handleCheckedCitiesChange(value) {
      const checkedCount = value.length
      this.checkAll = checkedCount === this.taskOptions.length
      this.isIndeterminate = checkedCount > 0 && checkedCount < this.taskOptions.length
    },
    doNext() {
      this.showDialog = false
      this.loading = true
      const that = this
      let count = 0
      const finishNum = that.infoList.length * that.checkTaskOptions.length * that.scoreTypeList.length
      that.infoList.forEach(el => {
        that.checkTaskOptions.forEach(item => {
          that.scoreTypeList.forEach(f => {
            const typeList = that.dict.type[f.value]
            const subjectName = typeList.map(el => el.value).join(',')
            const score = typeList.map(el => Math.floor(Math.random() * (10 - 6 + 1)) + 6).join(',')
            const obj = {
              'id': null,
              'stuId': el.stuId,
              'stuName': el.stuName,
              'period': item.taskName,
              'subjectName': subjectName,
              'score': score,
              'scorerId': null,
              'scorer': null,
              'scoreType': f.key,
              'createTime': null,
              'updateBy': null,
              'updateTime': null,
              'remark': null
            }

            addScore_info(obj).then((response) => {
              count += 1
              if (finishNum === count) {
                that.loading = false
                that.$modal.msgSuccess('批量新增成功')
                that.getList()
              }
            })
          })
        })
      })
    },
    changeTask(item) {
      this.form.period = item.taskName
    },
    getTaskList() {
      taskList().then((response) => {
        this.taskNameList = response.rows
        this.taskOptions = this.taskNameList
      })
    },
    /** 查询学生信息列表 */
    getStuList() {
      studentInfo({ pageNum: 1, pageSize: 1000 }).then(response => {
        this.infoList = response.rows
      })
    },
    /** 查询分数信息列表 */
    getList() {
      this.loading = true
      listScore_info(this.queryParams).then(response => {
        this.score_infoList = response.rows
        this.total = response.total
        this.loading = false
      })
    },
    changeStu(item) {
      this.form.stuId = item.grade
      this.form.stuName = item.stuName
    },
    changeType(item) {
      const fItem = this.scoreTypeList.find(el => el.key === item)
      this.typeList = this.dict.type[fItem.value]
    },
    getDict(item) {
      const obj = this.scoreTypeList.find(el => el.key === item)
      return this.dict.type[obj.value]
    },
    // 取消按钮
    cancel() {
      this.open = false
      this.reset()
    },
    // 表单重置
    reset() {
      this.form = {
        id: null,
        stuId: null,
        stuName: null,
        period: null,
        subjectName: [],
        score: [],
        scorerId: null,
        scorer: null,
        scoreType: null,
        createTime: null,
        updateBy: null,
        updateTime: null,
        remark: null
      }
      this.resetForm('form')
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1
      this.getList()
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm('queryForm')
      this.handleQuery()
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id)
      this.single = selection.length !== 1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset()
      this.open = true
      this.title = '添加分数信息'
      this.scoreList = []
      this.optType = 'add'
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset()
      const id = row.id || this.ids
      this.optType = 'edit'
      getScore_info(id).then(response => {
        this.form = response.data
        this.open = true
        this.title = '修改分数信息'
        this.scoreList = this.form.score.split(',')
      })
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs['form'].validate(valid => {
        if (valid) {
          this.form.subjectName = this.typeList.map(el => el.value).join(',')
          const arr = []
          this.scoreList.forEach(el => {
            arr.push(el || 0)
          })
          this.form.score = arr.join(',')
          if (this.form.id != null) {
            updateScore_info(this.form).then(response => {
              this.$modal.msgSuccess('修改成功')
              this.open = false
              this.getList()
            })
          } else {
            addScore_info(this.form).then(response => {
              this.$modal.msgSuccess('新增成功')
              this.open = false
              this.getList()
            })
          }
        }
      })
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id || row.ids || this.ids
      this.$modal
        .confirm(row.ids && row.ids.length ? `是否删除所有数据` : `是否删除此条数据`)
        .then(function() {
          return delScore_info(ids)
        })
        .then(() => {
          this.getList()
          this.$modal.msgSuccess('删除成功')
        })
        .catch(() => {})
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download('system/score_info/export', {
        ...this.queryParams
      }, `score_info_${new Date().getTime()}.xlsx`)
    }
  }
}
</script>
<style rel="stylesheet/scss" lang="scss">

.subject_score {
  display: flex;
  margin-bottom: 5px;
   .item {
    width: 200px;
    color: #606266;
    font-weight: 700;
   }
}
</style>
